package com._51cto.healthy.service;

import com._51cto.healthy.base.BaseMapper;
import com._51cto.healthy.content.P;
import com._51cto.healthy.mapper.UserMapper;
import com._51cto.healthy.pojo.User;
import com._51cto.healthy.utils.Md5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.common.utils.MD5Utils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;

import java.util.List;


@DubboService
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public BaseMapper<User> getDao() {
        return userMapper;
    }


    //用户名验证
    @Override
    public void validUsername(String username){
        //方法一
        //return userMapper.selectUserByUsername(username);

        //方法二
        //需要将返回值改为void
        User user = userMapper.selectUserByUsername(username);
        //使用断言  断言类似于if else
        Assert.notNull(user,"用户名不存在");

        //方法三
        //需要将返回值改为void
        //User user = userMapper.selectUserByUsername(username);
        //异常抛出 前端响应来到controller抛出异常并返回给service,service再向上抛出异常,被自定义异常类捕获并返回错误信息
        //if(user == null){
        //    throw new IllegalArgumentException("用户名不存在666");
        //}


    }

    //用户登录
    @Override
    public User login(String username, String password) {
        //根据用户名查询
        User user = userMapper.selectUserByUsername(username);
        String userPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        //把前端传回来的password与数据库password进行比较,如果不相等就抛出异常
        if (!user.getPassword().equals(userPassword)) {
            throw new IllegalArgumentException("用户名或密码错误");
        }
        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        //复用结果
        return userMapper.selectUserByUsername(username);
    }

    @Override
    public List<User> queryByRole(Integer roleId) {

       return userMapper.queryByRole(roleId);
    }



    @Override
    public P<User> queryUserRole(String query, Integer pageNum, Integer pageSize) {
        //开启分页
        PageHelper.startPage(pageNum,pageSize);
        //调用mapper层的方法
        List<User> users = userMapper.queryUserRole(query);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return new P().setPageSize(pageInfo.getPageSize())
                .setPageNum(pageInfo.getPageNum())
                .setPages(pageInfo.getPages())
                .setRows(pageInfo.getList())
                .setTotal(pageInfo.getTotal());
    }

    //修改密码
    @Override
    public void upPassword(User user) {
        String password = user.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);

        userMapper.upPassword(encode,user.getId());
    }

    @Override
    @Transactional
    public void insertInto( User user) {
        userMapper.insertInto(user);
        user.getRoleIds().forEach(roleId ->{
            userMapper.insetRoleId(user.getId(),roleId);
        });

        String imgName = getImgName(user.getAvatar());
        System.out.println(imgName);
        unUseImgRemove(imgName);

    }
    //截取图片名称
    private String getImgName(String imgUrl){
        return imgUrl.substring(imgUrl.lastIndexOf("/")+1);
    }
    //从列表中删除图片信息
    private void unUseImgRemove(String imgName) {
        redisTemplate.boundSetOps("UNUSE_IMG").remove(imgName);
    }

    //将图片信息加入列表
    private void unUseImgAdd(String imgName) {
        redisTemplate.boundSetOps("UNUSE_IMG").add(imgName);
    }

    @Override
    @Transactional
    public void updateUserRole(User user) {
        //查询老照片
        User old = userMapper.queryByPK(user.getId());
        String oldName = getImgName(old.getAvatar());
        //获取新照片的名字
        String imgName = getImgName(user.getAvatar());
        //修改用户管理
        userMapper.updateUserRole(user);
        String password = user.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);
        userMapper.upPassword(encode,user.getId());
        //删除用户管理下所属的角色管理
        userMapper.deleteRole(user.getId());
        //添加新的角色管理
        user.getRoleIds().forEach(rId ->{
            userMapper.insetRoleId(user.getId(),rId);
        });
        //判断图片是否存在或者为空
        if(!StringUtils.hasText(oldName)||oldName.equals(imgName)){
            return;
        }
        //老照片存入redis
        unUseImgAdd(oldName);
        //新照片在redis中移除
        unUseImgRemove(imgName);
    }

    @Override
    @Transactional
    public void deleteUserRole(Integer id) {
        User old = userMapper.queryByPK(id);
        String imgName = getImgName(old.getAvatar());
        //先删除角色管理关联表
        userMapper.deleteRole(id);
        //在删除角色管理
        int i = userMapper.deleteByPK(id);
        if(i >0 ){
            unUseImgAdd(imgName);
        }
    }

}
